using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using WindowsLive.Writer.Api;

namespace ClipboardCapture
{
    [WriterPlugin("d0969b32-1be4-4563-936c-5142ba80dc2f", "Clipboard Capture",
        PublisherUrl = "http://scottisafooldev.spaces.live.com",
        Description = "Allows you to insert an image from your clipboard and define the name of the image",
        ImagePath = "writer.png",
        HasEditableOptions = true)]
    [InsertableContentSource("Clipboard Image")]

    public class Plugin : ContentSource
    {
        private Settings defaultsettings;

        public override void Initialize(IProperties pluginOptions)
        {
            base.Initialize(pluginOptions);
            defaultsettings = new Settings(pluginOptions);
        }

        public override DialogResult CreateContent(IWin32Window dialogOwner, ref string content)
        {
            string path = string.Format(@"{0}SJL\", Path.GetTempPath());
            content = "";
            DialogResult result;
            if (Clipboard.GetDataObject() != null)
            {
                IDataObject data = Clipboard.GetDataObject();
                if (data.GetDataPresent(DataFormats.Bitmap))
                {
                    using (frmFileName form = new frmFileName(defaultsettings))
                    {
                        result = form.ShowDialog();
                        if (result == DialogResult.OK)
                        {
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
                            path += form.FileName;
                            path += ".";
                            path += form.FileFormat.ToString();
                            Image image = (Image)data.GetData(DataFormats.Bitmap, true);
                            image.Save(path, form.FileFormat);
                            content = string.Format("<img src=\"file://{0}\" alt=\"{1}\" />", path, form.FileName);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Sorry, your clipboard is not an image.", "Big Fat Hairy Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("Sorry, your clipboard is empty.", "Big Fat Hairy Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            return DialogResult.OK;
        }

        public override void EditOptions(IWin32Window dialogOwner)
        {
            frmOptions op = new frmOptions(defaultsettings);
            op.ShowDialog();
        }
    }
}
